package cn.xfyun.example.util;

import cn.xfyun.example.controller.SparkWebSocketHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SparkService {

    private final InterviewService interviewService;

    @Autowired
    public SparkService(InterviewService interviewService) {
        this.interviewService = interviewService;
    }

    private static final String hostUrl = "https://spark-api.xf-yun.com/v1/x1";
    private static final String domain = "x1";
    private static Gson gson = new Gson();
    private static StringBuilder reasoningContentTotal = new StringBuilder();
    private static StringBuilder contentTotal = new StringBuilder();
    private volatile long lastReceivedTime = System.currentTimeMillis();


    //存储最终生成的AI分析
    private static final ConcurrentHashMap<String, JSONObject> summary = new ConcurrentHashMap<>();
    /**
     * 直接提取并拼接reasoning_content和content字段内容
     * @param message 接收到的JSON消息字符串
     * @return 拼接后的结果，包含两个字段：reasingContentTotal 和 content总的
     */
    public static Map<String, String> processReceivedData(String message) {
        JSONObject jsonObject = JSON.parseObject(message);


        // 直接尝试获取payload.choices.text数组（不检查 header.code）
        if (jsonObject.containsKey("payload")) {
            JSONObject payload = jsonObject.getJSONObject("payload");
            if (payload.containsKey("choices")) {
                JSONObject choices = payload.getJSONObject("choices");
                if (choices.containsKey("text")) {
                    JSONArray textArray = choices.getJSONArray("text");

                    for (int i = 0; i < textArray.size(); i++) {
                        JSONObject textItem = textArray.getJSONObject(i);

                        // 提取reasoning_content（如果存在）
                        if (textItem.containsKey("reasoning_content")) {
                            reasoningContentTotal.append(textItem.getString("reasoning_content"));
                        }

                        // 提取content（如果存在）
                        if (textItem.containsKey("content")) {
                            contentTotal.append(textItem.getString("content"));
                        }
                    }
                }
            }
        }

        // 返回结果
        Map<String, String> result = new HashMap<>();
        result.put("reasingContentTotal", reasoningContentTotal.toString());
        result.put("contentTotal", contentTotal.toString());

        return result;
    }

    public Map<String, String> askQuestion(String appid, String apiSecret, String apiKey, String newQuestion, String sessionId,String interviewId) throws Exception {
        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        // ✅ 传递 SparkService 实例
        WebSocket webSocket = client.newWebSocket(request, new SparkWebSocketListener(this, appid, newQuestion, sessionId, interviewId));
        return processReceivedData(reasoningContentTotal.toString(), contentTotal.toString());
    }

    private static Map<String, String> processReceivedData(String reasoningContent, String content) {
        Map<String, String> result = new HashMap<>();
        result.put("reasoningContent", reasoningContent);
        result.put("content", content);
        return result;
    }

    private static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "GET " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();
        return httpUrl.toString();
    }

    private static class SparkWebSocketListener extends WebSocketListener {
        private final String interviewId;  // 新增字段
        private final SparkService sparkService; // ✅ 新增实例引用
        private final String appid;
        private final String newQuestion;
        private final String sessionId; // 新增字段
        private boolean wsCloseFlag = false;

        public SparkWebSocketListener(SparkService sparkService, String appid, String newQuestion, String sessionId,String interviewId) {
            this.sparkService = sparkService;
            this.appid = appid;
            this.newQuestion = newQuestion;
            this.sessionId = sessionId;
            this.interviewId = interviewId;
        }

        @Override
        public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
            super.onOpen(webSocket, response);
            MyThread myThread = new MyThread(webSocket,sparkService,interviewId);
            myThread.start();
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {

            Map<String, String> processedData = processReceivedData(text);

            String reasingContent = processedData.get("reasingContentTotal");
            String content = processedData.get("contentTotal");

            // 构建 JSON 消息
            JSONObject jsonMessage = new JSONObject();

            if (content != null && !content.isEmpty()) {
                // content 已生成，仅发送 contentTotal ，且保存
                jsonMessage.clear();
                jsonMessage.put("contentTotal", content);
            } else if (reasingContent != null && !reasingContent.isEmpty()) {
                // content 未生成，发送 reasingContentTotal
                jsonMessage.put("reasingContentTotal", reasingContent);
            }
            summary.put(sessionId, jsonMessage);
//            System.out.println("接收到的数据：" + jsonMessage);

            try {
                SparkWebSocketHandler.sendMessageToClient(sessionId, String.valueOf(jsonMessage)); // 发送消息
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
            if (myJsonParse.header.code != 0) {
                System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
                System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
                webSocket.close(1000, "");
            }
            if (myJsonParse.header.status == 2) {
                wsCloseFlag = true;
            }
        }

        @Override
        public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            try {
                if (null != response) {
                    int code = response.code();
                    System.out.println("onFailure code:" + code);
                    assert response.body() != null;
                    System.out.println("onFailure body:" + response.body().string());
                    if (101 != code) {
                        System.out.println("connection failed");
                        System.exit(0);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        class MyThread extends Thread {
            private final WebSocket webSocket;
            private final String interviewId;  // 新增字段
            private final SparkService sparkService; // ✅ 持有实例

            public MyThread(WebSocket webSocket, SparkService sparkService,String interviewId) { // ✅ 参数注入
                this.webSocket = webSocket;
                this.sparkService = sparkService;
                this.interviewId = interviewId;
            }

            public void run() {
                try {
                    JSONObject requestJson = new JSONObject();
                    JSONObject header = new JSONObject();
                    header.put("app_id", appid);
                    header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                    JSONObject parameter = new JSONObject();
                    JSONObject chat = new JSONObject();
                    chat.put("domain", domain);
                    chat.put("temperature", 0.5);
                    chat.put("max_tokens", 4096);
                    parameter.put("chat", chat);

                    JSONObject payload = new JSONObject();
                    JSONObject message = new JSONObject();
                    JSONArray text = new JSONArray();
                    RoleContent roleContent = new RoleContent();
                    roleContent.role = "user";
                    roleContent.content = newQuestion;
                    text.add(JSON.toJSON(roleContent));

                    message.put("text", text);
                    payload.put("message", message);

                    requestJson.put("header", header);
                    requestJson.put("parameter", parameter);
                    requestJson.put("payload", payload);
                    webSocket.send(requestJson.toString());

                    while (!wsCloseFlag) {
                        Thread.sleep(200);
                    }
                    // ✅ 使用实例方法替代静态调用
                    sparkService.interviewService.updateSummaryAndStatus(interviewId, summary);
                    System.out.println("连接已关闭");
                    webSocket.close(1000, "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class JsonParse {
        Header header;
        Payload payload;
    }

    static class Header {
        int code;
        int status;
        String sid;
    }

    static class Payload {
        Choices choices;
    }

    static class Choices {
        List<Text> text;
    }

    static class Text {
        String role;
        String content;
    }

    static class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}